package com.yuzhi.master.sewageTreatment.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yuzhi.common.core.page.PageDataInfo;
import com.yuzhi.common.util.StringUtils;
import com.yuzhi.master.sewageTreatment.domain.request.SewageTreatmentReq;
import com.yuzhi.master.sewageTreatment.entity.SwageTreatmentEntity;
import com.yuzhi.master.sewageTreatment.entity.SwageTreatmentEntityReq;
import com.yuzhi.master.sewageTreatment.entity.SwageTreatmentEntityVo;
import com.yuzhi.master.sewageTreatment.mapper.SewageTreatmentMapper;
import com.yuzhi.master.sewageTreatment.service.SewageTreatmentService;
import com.yuzhi.system.domain.vo.SysOssVo;
import com.yuzhi.system.service.ISysOssService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.locationtech.jts.geom.Coordinate;
import org.locationtech.jts.geom.Geometry;
import org.locationtech.jts.geom.LinearRing;
import org.locationtech.jts.geom.Polygon;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@RequiredArgsConstructor
@Service
public class SewageTreatmentServiceImpl extends ServiceImpl<SewageTreatmentMapper, SwageTreatmentEntity>
        implements SewageTreatmentService {


    private final SewageTreatmentMapper sewageTreatmentMapper;

    private final ISysOssService iSysOssService;
    /**
     * 保存污水处理厂信息
     *
     * @param entity 污水处理厂实体
     * @return 保存结果
     */
    @Override
    public boolean save(SwageTreatmentEntity entity) {
        return super.save(entity);
    }

    @Override
    public PageDataInfo pageByCondition(SewageTreatmentReq req) {
        return PageDataInfo.build();
    }

    /**
     * 坐标转换
     *
     * @param swageTreatmentEntity
     */
    private static void coordinateConversion(SwageTreatmentEntity swageTreatmentEntity) {
        try {
            // 处理几何坐标转换
            Geometry geometry = swageTreatmentEntity.getFactAreaGeo();
            if (geometry != null && !geometry.isEmpty()) {
                // 将POLYGON转换为前端需要的坐标数组格式
                List<List<Double>> coordinates = new ArrayList<>();

                // 获取多边形的外环
                LinearRing exteriorRing = ((Polygon) geometry).getExteriorRing();

                // 遍历外环上的点
                for (int i = 0; i < exteriorRing.getNumPoints(); i++) {
                    Coordinate coord = exteriorRing.getCoordinateN(i);
                    List<Double> point = new ArrayList<>();
                    point.add(coord.x);  // 经度
                    point.add(coord.y);  // 纬度
                    coordinates.add(point);
                }

                // 可以移除最后一个点，因为POLYGON会首尾相接重复第一个点
                if (coordinates.size() > 1 && coordinates.get(0).equals(coordinates.get(coordinates.size() - 1))) {
                    coordinates.remove(coordinates.size() - 1);
                }

                // 将转换后的坐标设置到中，需要在中添加一个字段来存储
                swageTreatmentEntity.setCoordinates(coordinates);
            }
        } catch (Exception e) {
            log.error("坐标转换失败", e);
            e.printStackTrace();
        }
    }

    /**
     * 更新污水处理厂信息
     *
     * @param entity 待更新的实体
     * @return 更新结果
     */
    @Override
    public boolean updateById(SwageTreatmentEntity entity) {
        return sewageTreatmentMapper.updateById(entity) > 0;
    }


    /**
     * 根据工厂ID查询详情
     *
     * @param id 主键
     * @return 污水处理厂实体
     */
    @Override
    public SwageTreatmentEntity getById(String id) {
        SwageTreatmentEntity entityList = sewageTreatmentMapper.selectById(id);
        coordinateConversion(entityList);
        return entityList;
    }


    /**
     * 获取污水厂数据
     *
     * @return
     */
    public List<SwageTreatmentEntity> getSwageTreatmentList() {
        LambdaQueryWrapper<SwageTreatmentEntity> query = new LambdaQueryWrapper<>();
        query.orderByAsc(SwageTreatmentEntity::getFactId);
        return sewageTreatmentMapper.selectList(query);

    }

    /**
     * 根据污水厂代码查询污水厂信息
     *
     * @param factId
     * @return
     */
    public List<SwageTreatmentEntity> getSwageTreatmentByFactId(String factId) {
        LambdaQueryWrapper<SwageTreatmentEntity> query = new LambdaQueryWrapper<>();
        query.eq(StringUtils.isNotBlank(factId), SwageTreatmentEntity::getFactId, factId);
        return sewageTreatmentMapper.selectList(query);
    }

    @Override
    public List<String> getImageUrlsByOssIds(List<String> ossIds) {
        if (CollectionUtils.isEmpty(ossIds)) return Collections.emptyList();

        return iSysOssService.listByIds(ossIds)
                .stream()
                .map(SysOssVo::getOriginalName)
                .collect(Collectors.toList());
    }

    /**
     * 导出污水厂列表
     *
     * @param request
     * @return
     */
    @Override
    public List<SwageTreatmentEntityVo> queryList(SwageTreatmentEntityReq request) {
        LambdaQueryWrapper<SwageTreatmentEntity> lqw = Wrappers.lambdaQuery();
        lqw.like(StringUtils.isNotBlank(request.getFactName()), SwageTreatmentEntity::getFactName, request.getFactName());
        lqw.eq(StringUtils.isNotBlank(request.getAreaCode()), SwageTreatmentEntity::getAreaCode, request.getAreaCode());
        return sewageTreatmentMapper.selectVoList(lqw);
    }


    /**
     * 保存污水厂点位信息
     *
     * @param id
     * @param areaCoordinates
     * @return
     */
    @Override
    public int savePoint(String id, List<List<Double>> areaCoordinates) {
        return sewageTreatmentMapper.savePoint(id, areaCoordinates);
    }
}
